package com.beiding.jsonanalyzer.analyze.func.openfunc;

import com.beiding.jsonanalyzer.analyze.func.OneFunc;
import com.beiding.jsonanalyzer.analyze.func.base.EasyFunc;
import com.beiding.jsonanalyzer.analyze.func.base.OneFuncAdaptor;

import java.util.Collection;

/**
 * 获取字符串或者集合的长度
 *
 * @author 丁常磊
 * @date 2022/5/19 11:23
 */

public class Len {

    public static OneFunc of(Object key) {
        return FuncUtils.buildForEasyFunc(new OneFuncAdaptor<EasyFunc>() {
            @Override
            protected EasyFunc newInstance() {
                return new EasyFunc() {
                    @Override
                    protected Object execute(Object v) {
                        if (v instanceof String) {
                            return ((String) v).length();
                        } else if (v instanceof Collection) {
                            return ((Collection) v).size();
                        } else if (v instanceof Object[]) {
                            return ((Object[]) v).length;
                        }
                        return null;
                    }

                    @Override
                    public String toString() {
                        return "len(" + core + ")";
                    }
                };
            }
        }, key);
    }


}
